//
// Created by swe_dev on 25-1-30.
//

#ifndef INCUBATOR_BRUSHLESS_ESC_HPP
#define INCUBATOR_BRUSHLESS_ESC_HPP

#include "task.hpp"
#include "tim/pwm_generator.hpp"

class BrushlessEsc : public Task {
public:

    BrushlessEsc() {
        period_ms = 50U;
    }

    void init_task() override {
        esc_pwm = std::make_unique<PwmGenerator>(&htim3, TIM_CHANNEL_4);
        auto ret = esc_pwm->init();
        CCLOG(SWEN_INFO, "[TEST|PUT|FAN_PWM_INIT|%s]", (ret == HAL_OK) ? "PASS" : "FAIL");
        esc_pwm->set_duty(0);
        task_yield(1000);
        esc_pwm->set_duty(2000);
        task_yield(5000);
        esc_pwm->set_duty(1000);
        task_yield(5000);
//        esc_pwm->set_duty(1090);
//        task_yield(500);
//        esc_pwm->set_duty(1065);
    }

    void period_task() override {
        static uint32_t duty = 1000U;
        auto value = HAL_GPIO_ReadPin(GPIOE, GPIO_PIN_4);
        if (value == 0) {
            HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_5);
            if (duty <= 1000U) {
                duty = 1065U;
            } else {
                duty = 1000U;
            }
            task_yield(200U);
        }
        esc_pwm->set_duty(duty);
    }

protected:
    std::unique_ptr<PwmGenerator> esc_pwm{nullptr};
};

#endif //INCUBATOR_BRUSHLESS_ESC_HPP
